//
//  WmcTextView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/11.
//

import UIKit

// MARK: - [WmcTextView]

class WmcTextView: WmcBaseView {
    // Lifecycle

    convenience init(placeholder: String, maxCount: Int) {
        self.init(frame: .zero)
        font = 16.wmc_font
        self.placeholderLabel.text = placeholder
        self.maxCount = maxCount
        backgroundColor = .wmc_grayH19_F5F5F5
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required convenience init() {
        self.init(placeholder: "请输入内容", maxCount: 100)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Internal

    
    lazy var textView: UITextView = {
        let textView = UITextView()
        textView.textColor = .wmc_grayH2_323233
        textView.backgroundColor = .clear
        textView.textContainerInset = textView.textContainerInset
            .yp.set(left: 12)
            .yp.set(top: Wmc_standardEdge.top)
            .yp.set(right: 3)
        textView.delegate = self
        return textView
    }()

    lazy var placeholderLabel: UILabel = {
        let label = UILabel.YP.Create(color: UIColor.wmc_grayH8_8A8A99,
                                      alignment: .left)
        label.numberOfLines = 0
        return label
    }()

    lazy var countLabel: UILabel = {
        let label = UILabel.YP.Create(font: 16.wmc_font,
                                      color: UIColor.wmc_grayH8_8A8A99,
                                      alignment: .left)
        return label
    }()

    lazy var clearBtn: UIButton = {
        let btn = UIButton.Wmc_textColorBtn(color: .wmc_mainTheme, title: "清空内容")
        btn.titleLabel?.font = 14.wmc_font
        return btn
    }()

    var maxCount: Int = 100

    var font: UIFont? {
        set {
            textView.font = newValue
            placeholderLabel.font = newValue
        }
        get { textView.font }
    }

    var text: String? {
        set {
            textView.text = newValue
            textViewDidChange(textView)
        }
        get { textView.text }
    }

    override func makeUI() {
        layer.cornerRadius = 4
        layer.masksToBounds = true

        addSubview(textView)
        textView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(-37)
        }

        addSubview(placeholderLabel)
        placeholderLabel.snp.makeConstraints { make in
            make.left.equalTo(textView.textContainerInset.left + 4.5)
            make.top.equalTo(textView.textContainerInset.top + 0.5)
            make.right.equalToSuperview()
        }

        addSubview(countLabel)
        countLabel.snp.makeConstraints { make in
            make.left.equalTo(placeholderLabel)
            make.bottom.equalTo(-Wmc_standardEdge.bottom)
            make.right.equalTo(self.snp.centerX)
        }

        addSubview(clearBtn)
        clearBtn.snp.makeConstraints { make in
            make.right.bottom.equalToSuperview()
            let btnSize = CGSize(width: 80, height: Wmc_standardEdge.yp.vertical + 20)
            make.size.equalTo(btnSize)
        }

        clearBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.textView.text = ""
            weakSelf.textViewDidChange(weakSelf.textView)
        }

        textViewDidChange(textView)
    }
}

// MARK: UITextViewDelegate

extension WmcTextView: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        guard var text = textView.text else { return }

        if let lang = textView.textInputMode?.primaryLanguage,
           lang == "zh-Hans",
           let selectRange = textView.markedTextRange {
            let position = textView.position(from: selectRange.start, offset: 0)
            if position == nil {
                if text.count > maxCount {
                    text = text.yp.keepPrefix(count: maxCount)
                    textView.text = text
                }
            }
        } else {
            if text.count > maxCount {
                text = text.yp.keepPrefix(count: maxCount)
                textView.text = text
            }
        }
        let textCount = text.count
        countLabel.text = "\(textCount)/\(maxCount)"
        clearBtn.isHidden = textCount == 0
        placeholderLabel.isHidden = !clearBtn.isHidden
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        var isEffective = true
        switch textView.returnKeyType {
        case .done:
            if text == "\n" {
                textView.resignFirstResponder()
                isEffective = false
            }
        default: break
        }
        return isEffective
    }
}
